package com.wuzihao.disk.Recycle.service;

import com.wuzihao.disk.mybatis.flexigrid.PagingEntity;
import com.wuzihao.disk.mybatis.flexigrid.TblResponseEntity;
import com.wuzihao.disk.Recycle.entity.FileEntity;
import com.wuzihao.disk.Recycle.repository.FileRepository;
import com.wuzihao.disk.spring.security.UserDiskEntity;
import com.wuzihao.disk.file.service.FileService;
import com.wuzihao.disk.mybatis.entity.PtFileEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RecycleService {

    private static final Logger logger = LoggerFactory.getLogger(RecycleService.class);

    @Resource
    private FileRepository fileRepository;

    @Resource
    private FileService fileService;

    public TblResponseEntity<FileEntity> queryRecycleFiles(FileEntity searchEntity, PagingEntity paging) {
        // 获取当前登录用户ID
        String userId = getCurrentUserId();

        TblResponseEntity<FileEntity> response = new TblResponseEntity<>();
        int total = fileRepository.countRecycleFiles(userId, searchEntity);
        response.setTotal(total);

        paging.deal(FileEntity.class, total);
        response.setPage(paging.getPage());

        List<FileEntity> files = fileRepository.queryRecycleFilesByUser(userId, searchEntity, paging);
        response.setRawRecords(files);
        response.deal();

        return response;
    }

    // 保持向后兼容的方法
    public TblResponseEntity<FileEntity> queryRecycleFiles(PagingEntity paging) {
        return queryRecycleFiles(new FileEntity(), paging);
    }

    @Transactional
    public void restoreFile(String fileId) {
        String userId = getCurrentUserId();

        logger.info("准备恢复文件 - fileId: {}, userId: {}", fileId, userId);

        // 第一步：将文件信息从回收站插入到原文件表
        int insertCount = fileRepository.insertToFile(fileId, userId);
        logger.info("插入原文件表结果: {}", insertCount);
        if (insertCount == 0) {
            throw new RuntimeException("文件不存在或无权限恢复");
        }

        // 第二步：从回收站中删除
        int deleteCount = fileRepository.deleteFromTrash(fileId, userId);
        logger.info("从回收站删除结果: {}", deleteCount);
        if (deleteCount == 0) {
            throw new RuntimeException("从回收站删除记录失败");
        }
    }

    public void deletePermanently(String fileId) {
        String userId = getCurrentUserId();
        fileRepository.deletePermanently(fileId, userId);
    }

    @Transactional
    public void moveToRecycle(String fileId) {
        String userId = getCurrentUserId();

        // 调试：查看文件信息
        PtFileEntity fileInfo = fileService.queryFileInfoById(fileId);
        logger.info("准备删除文件 - fileId: {}, userId: {}", fileId, userId);
        if (fileInfo != null) {
            logger.info("文件信息 - fileName: {}, userUuid: {}, delFlag: {}",
                       fileInfo.getFileName(), fileInfo.getUserUuid(), fileInfo.getDelFlag());
        } else {
            logger.warn("文件不存在: {}", fileId);
            throw new RuntimeException("文件不存在");
        }

        // 第一步：将文件信息插入到回收站表
        int insertCount = fileRepository.insertToTrash(fileId, userId);
        logger.info("插入回收站结果: {}", insertCount);
        if (insertCount == 0) {
            throw new RuntimeException("文件不存在或无权限删除");
        }

        // 第二步：从原文件表中删除
        int deleteCount = fileRepository.deleteFromFile(fileId, userId);
        logger.info("删除原文件结果: {}", deleteCount);
        if (deleteCount == 0) {
            throw new RuntimeException("删除原文件记录失败");
        }
    }

    // 获取当前登录用户ID
    private String getCurrentUserId() {
        // 从SecurityContext获取UserDiskEntity，然后获取用户UUID
        UserDiskEntity userDiskEntity = (UserDiskEntity) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        return userDiskEntity.getUserUuid();
    }
}
